#include "tplate.h"
#include <fstream>
#include <iostream>
using namespace std;

void load_template_3D(tplate* tp, char* fn)
{
    // in fact a 2D tempalte
    ifstream tpfile;
    tpfile.open(fn);
    tpfile >> tp->tpsize;
    tp->pos = new int[tp->tpsize * 2];
    for (int i = 0; i < tp->tpsize; i++)
    {
        tpfile >> tp->pos[i * 2];
        tpfile >> tp->pos[i * 2 + 1];
    }
    tpfile.close();
    return;
}

void get_dv_3D(data_event_cont* dv, tplate* tp, float* target,
    int length, int width, int x, int y, int max_dv)
{
    //in it only read 2d data event
    dv->dvsize = 0;
    for (int i = 0; i < tp->tpsize; i++)
    {
        int px = x + tp->pos[i * 2];
        int py = y + tp->pos[i * 2 + 1];
        if ((px < 0) || px >= length)
            continue;
        if ((py < 0) || py >= width)
            continue;
        bool found = false;
        float values_1 = target[px * width + py];
        float values_2 = target[px * width + py + length * width];
        float values_3 = target[px * width + py + length * width * 2];
        if ((values_1 - (-1)) > 1e-6)
            found = true;
        if (found == true)
        {
            int cur_dvpos = dv->dvsize;
            dv->tpos[cur_dvpos] = i;
            dv->pos[cur_dvpos * 2] = (tp->pos[i * 2]);
            dv->pos[cur_dvpos * 2 + 1] = (tp->pos[i * 2 + 1]);
            dv->value[cur_dvpos * 3] = values_1;
            dv->value[cur_dvpos * 3 + 1] = values_2;
            dv->value[cur_dvpos * 3 + 2] = values_3;
            dv->dvsize++;
            if (max_dv <= dv->dvsize)
                break;
        }
    }
    return;
}
